package com.atstudy.channel;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2022/12/30 9:23
 * @copyright: 博为峰
 */
public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
//        m1();
//        m2();
        RandomAccessFile file = new RandomAccessFile("C:\\Users\\admin\\Desktop\\java29\\io\\bos.txt", "rw");
        //建立通道
        FileChannel channel = file.getChannel();
        //字节缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //数据
        String str = "def";
        //存储数据到字节缓冲区
        byteBuffer.put(str.getBytes());
        //读写转换
        byteBuffer.flip();
        //写数据
        channel.write(byteBuffer);
        //g关闭
        channel.close();

    }

    private static void m2() throws IOException {
        RandomAccessFile file = new RandomAccessFile("C:\\Users\\admin\\Desktop\\java29\\io\\bos.txt", "rw");
        //建立通道
        FileChannel channel = file.getChannel();
        //字节缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int len = 0;
        while ((len = channel.read(byteBuffer)) != -1){
            //读写转换
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()){
                byte b = byteBuffer.get();
                System.out.println((char)b);
            }
            byteBuffer.clear();
        }
    }

    private static void m1() throws IOException {
        RandomAccessFile file = new RandomAccessFile("C:\\Users\\admin\\Desktop\\java29\\io\\bos.txt", "rw");
        //建立通道
        FileChannel channel = file.getChannel();
        //字节缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //读
        int len = channel.read(byteBuffer);

        System.out.println(len);

        //读写转换
        byteBuffer.flip();

        byte b = byteBuffer.get();

        System.out.println((char)b);
    }
}
